<?php
// +----------------------------------------------------------------------
// | B5Yii2CMF V3.0 [快捷通用基础管理开发平台]
// +----------------------------------------------------------------------
// | Author=>冰舞 <357145480@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\system;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\Role;
use common\services\system\RoleService;
use common\services\system\RoleUserService;

class RoleController extends AuthController
{
    use CommonAction;

    protected string $model = Role::class;
    protected bool $validate = true;

    // 获取当前登录用户的可操作角色列表
    public function actionGetSelect(): array
    {
        return $this->success('', ['list' => RoleService::selectRoleUserSelectList($this->user_id)]);
    }

    /**
     * 数据权限操作
     * @return array
     */
    public function actionDataScope(): array
    {
        $roleId = intval($this->request->post('id', 0));
        if ($roleId < 1) return $this->error('参数错误');

        $role = Role::findOne($roleId);
        if (!$role) return $this->error('角色信息不存在');

        $role->data_scope = intval($this->request->post('data_scope', 0));
        if ($role->save(false) === false) return $this->error('保存失败');

        RoleService::updateRoleDeptIds($roleId, $this->request->post('dept_ids', []));
        return $this->success();
    }

    /**
     * 分配角色列表
     * @return array
     */
    public function actionAuthList(): array
    {
        $roleId = intval($this->request->post('roleId', 0));
        if ($roleId < 1) return $this->error('参数错误');
        $result = RoleUserService::selectAuthUsersPage($roleId, $this->request->post());
        return $this->success('', $result);
    }

    /**
     * 获取某个角色的未授权用户列表
     * @return array
     */
    public function actionGetAdminAuth(): array
    {
        $roleId = intval($this->request->post('roleId', 0));
        if ($roleId < 1) return $this->error('参数错误');
        $result = RoleUserService::selectUnAllocatedListPage($roleId, $this->request->post());
        return $this->success('', $result);
    }

    /**
     * 添加角色用户
     * @return array
     */
    public function actionAuthAppend(): array
    {
        $roleId = intval($this->request->post('roleId', 0));
        if ($roleId < 1) return $this->error('参数错误');
        $adminIds = trim($this->request->post('adminIds', ''));
        $res = RoleUserService::addRoleAllocatedAdmin($roleId, $adminIds);
        if ($res) return $this->success();
        return $this->error();
    }

    /**
     * 删除角色用户，取消授权
     * @return array
     */
    public function actionAuthRemove(): array
    {
        $adminIds = trim((string)$this->request->post('adminIds', ''));
        $roleId = intval($this->request->post('roleId', 0));
        if (!$adminIds || $roleId < 1) return $this->error('参数缺失');
        RoleUserService::deleteRoleUser($roleId, $adminIds);
        return $this->success();
    }

    protected function infoAfter(Role $model): array
    {
        $info = $model->toArray();
        $info['menu_ids'] = $model->menuIds ? array_column($model->menuIds, 'menu_id') : [];
        $info['dept_ids'] = $model->deptIds ? array_column($model->deptIds, 'dept_id') : [];
        return $this->success('', ['info' => $info]);
    }

    protected function saveBefore(Role $model, string $type): string
    {
        if ($type == 'edit') {
            if (!RoleService::checkHasRolePerm($this->user_id, $model->id)) {
                return '无权限此操作';
            }

            if ($model['id'] == $this->app->params['root_role_id']) {
                return '不允许操作超级管理员角色';
            }
        }
        return '';
    }

    protected function saveAfter(Role $model, string $type): void
    {
        if ($type == 'add' || $type == 'edit') { // 更新角色菜单
            RoleService::updateRoleMenuIds($model->id, $this->request->post('menu_ids', []));
        }
    }
}
